import requests
from spider.data_source.jsl.jsl_config import jsl_user, jsl_api, jsl_user_dict
# from spider.data_source.jsl import session
from db.sql_db import JslUserInfo
import json
from sqlalchemy import exc
from utils.mail_utils import send_mail

CHECK_LOGIN = 'https://www.jisilu.cn/webapi/account/unread/'


def get_cookie_str(db_instance):
    """
    获取登录cookie，过期自动登录，如果账号密码错误，返回None
    :return:
    """
    try:
        user = db_instance.session.query(JslUserInfo).filter(JslUserInfo.username == jsl_user.org_username).first()
    except exc.OperationalError:
        send_mail('量化程序数据库错误', "2006, MySQL server has gone away (BrokenPipeError(32, Broken pipe))")
    # 第一次使用user为空
    if user is None:
        return refresh_cookie(db_instance)
    cookie_str = _get_cookie_str(user)
    if not check_login(cookie_str):
        return refresh_cookie(db_instance)
    return cookie_str


def check_login(cookie_str):
    response = requests.get(
        url=CHECK_LOGIN,
        headers={
            "Cookie": cookie_str,
            "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
        },
    )
    result = json.loads(response.text)
    data = result['data']
    if data is None:
        return False
    return True


def _get_cookie_str(user):
    cookie_str = "kbzw__Session={}; kbzw_r_uname={}; kbzw__user_login={}".format(user.kbzw__Session, user.kbzw_r_uname,
                                                                                 user.kbzw__user_login)
    return cookie_str


def refresh_cookie(db):
    try:
        login(db)
        user = db.session.query(JslUserInfo).filter(JslUserInfo.username == jsl_user.org_username).first()
    except Exception as e:
        print('jsl账号或密码错误')
        print(e)
        return None
    cookie_str = "kbzw__Session={}; kbzw_r_uname={}; kbzw__user_login={}".format(user.kbzw__Session, user.kbzw_r_uname,
                                                                                 user.kbzw__user_login)
    return cookie_str


# 通过返回值header中的Set-Cookie 提取出三个关键header
def get_info_from_cookie(cookie_getted):
    session_list = cookie_getted.split(";")
    kbzw__Session = session_list[0].split("=")[-1]
    kbzw_r_uname = ""
    kbzw__user_login = ""
    for item in session_list:
        if "kbzw_r_uname" in item:
            kbzw_r_uname = item.split("=")[-1]
        if "kbzw__user_login" in item:
            kbzw__user_login = item.split("=")[-1]
    return kbzw__Session, kbzw_r_uname, kbzw__user_login


def login(db):
    try:
        response = requests.post(
            url=jsl_api.login_url,
            headers={
                "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
            },
            data=jsl_user_dict(jsl_user)
        )
        print('Response HTTP Status Code: {status_code}'.format(
            status_code=response.status_code))
        print('Response HTTP Response Body: {content}'.format(
            content=response.content))
        print('Response HTTP Response Header: {header}'.format(
            header=response.headers))
        header = response.headers
        get_cookie = header.get('Set-Cookie')
        kbzw_session, kbzw_uname, kbzw_login = get_info_from_cookie(get_cookie)
        user = db.session.query(JslUserInfo).filter(JslUserInfo.username == kbzw_uname).first()
        if user is not None:
            user.username = kbzw_uname
            user.kbzw__Session = kbzw_session
            user.kbzw_r_uname = kbzw_uname
            user.kbzw__user_login = kbzw_login
        else:
            print(header.get('kbzw_r_uname'))
            new_user = JslUserInfo(username=kbzw_uname,
                                   kbzw__Session=kbzw_session,
                                   kbzw__user_login=kbzw_login,
                                   kbzw_r_uname=kbzw_uname
                                   )
            db.session.add(new_user)
        db.session.commit()
        # session.close()
    except requests.exceptions.RequestException:
        print('HTTP Request failed')


# login()

if __name__ == '__main__':
    login()
